package com.heima.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.heima.dto.CourseDto;
import com.heima.mapper.CourseMapper;
import com.heima.pojo.Course;
import com.heima.service.CourseService;
import com.heima.vo.CourseVo;
import com.heima.vo.FieldListVo;
import com.heima.vo.PageResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.util.List;

@Service
@Slf4j
public class CourseServiceImpl implements CourseService {
    @Autowired
    private CourseMapper courseMapper;

    @Override
    public PageResult list(CourseDto courseDto) {
        PageHelper.startPage(courseDto.getPageNum(),courseDto.getPageSize());
        Page<CourseVo> page =courseMapper.pageQueryCourse(courseDto);
        PageResult result = new PageResult();
        result.setTotal(page.getTotal());
        result.setRows(page.getResult());
        return result;
    }

    /**
     * 课程下拉框
     * @param
     * @return
     */
    @Override
    public FieldListVo listselect() {
        List<Course> list = courseMapper.listselect();
        FieldListVo fieldVo = new FieldListVo();
        fieldVo.setData(list);
        return fieldVo;
    }

    /**
     * 新增课程
     * @param courseVo
     */
    @Override
    public void addCourse(CourseVo courseVo) {
        Course course = new Course();
        course.setName(courseVo.getName());
        course.setPrice(courseVo.getPrice());
        course.setApplicablePerson(courseVo.getApplicablePerson());
        course.setInfo(courseVo.getInfo());
        course.setSubject(courseVo.getSubject());
        course.setCreateTime(LocalDateTime.now());
        courseMapper.addCourse(course);
    }

    /**
     * 根据id查询课程信息
     * @param id
     * @return
     */
    @Override
    public CourseVo getById(Integer id) {
        CourseVo coursevo = courseMapper.getById(id);
        return coursevo;
    }

    /**
     * 修改课程信息
     * @param courseVo
     */
    @Override
    public void updateCourse(CourseVo courseVo) {
        Course course = new Course();
        BeanUtils.copyProperties(courseVo,course);
        courseMapper.updateCourse(course);
    }

    /**
     * 删除课程
     * @param ids
     */
    @Override
    @Transactional
    public void deleteById(List<Integer> ids) {
        //防止传入的课程id集合为空
        if (CollectionUtils.isEmpty(ids)){
            return;
        }
        //遍历集合，删除
        for (Integer id : ids) {
            //判断该课程下是否有合同，有则不能删除
            //查询签约该课程的合同数量
            int count = courseMapper.selectCountById(id);
            if(count>0){
                throw new RuntimeException("该课程下有合同，不能删除");
            }
            courseMapper.deleteById(id);
        }
    }
}

